package com.zlsy.secondtime.threadcoreknowledge.threadobjectclasscommonmethods;

/**
 * @author zhouliang
 * @date 2020/5/17 12:19
 * <p>
 * 证明wait只释放当前的那把锁
 */
public class WaitNotifyReleaseOwnMonitor implements Runnable {

    private static final Object LOCK1 = new Object();
    private static final Object LOCK2 = new Object();

    @Override
    public void run() {
        synchronized (LOCK1) {
            System.out.println(Thread.currentThread().getName() + " GOT LOCK1 ");
            synchronized (LOCK2) {
                System.out.println(Thread.currentThread().getName() + " GOT LOCK2 ");

                System.out.println(Thread.currentThread().getName() + " Release LOCK1 ! ");
                try {
                    LOCK1.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static void main(String[] args) throws InterruptedException {
        WaitNotifyReleaseOwnMonitor r = new WaitNotifyReleaseOwnMonitor();
        Thread thread = new Thread(r);
        thread.setName("线程A");
        thread.start();

        Thread.sleep(1000L);

        Thread b = new Thread(new Runnable() {
            @Override
            public void run() {
                synchronized (LOCK1) {
                    System.out.println(Thread.currentThread().getName() + " GOT LOCK1 !");

                    System.out.println(Thread.currentThread().getName() + " TRY TO GOT LOCK2 !");
                    synchronized (LOCK2) {
                        System.out.println(Thread.currentThread().getName() + " GOT LOCK2 !");
                    }
                }
            }
        });
        b.setName("线程B");
        b.start();
    }
}
